package com.hinotoyk.testsystem.config;

import com.hinotoyk.testsystem.mappers.TeacherMapper;
import com.hinotoyk.testsystem.service.TeacherService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @program: testsystem
 * @description:
 * @author: DYJ
 * @create: 2019-11-14 09:56
 **/
public class TeacherRealm extends AuthorizingRealm {

    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private TeacherService teacherService;

    @Resource
    private SessionDAO sessionDAO;

    /**
     * 获取授权信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 获取身份验证信息
     * Shiro中，最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
     *
     * @param authenticationToken 用户身份信息 token
     * @return 返回封装了用户信息的 AuthenticationInfo 实例
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("————Teacher身份认证方法————");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String password = new String(token.getPassword());

        // 从数据库获取对应用户名密码的用户
        String passwordInDB = teacherMapper.getPassword(token.getUsername());
        if (null == passwordInDB) {
            throw new AccountException("用户名不正确");
        }

        ByteSource salt = ByteSource.Util.bytes(token.getUsername());

        String md5Password = new SimpleHash("MD5",
                new String((char[]) token.getCredentials()),
                salt,
                1024).toHex();

        if (!passwordInDB.equals(md5Password)) {
            throw new AccountException("密码不正确");
        }


//        Collection<Session> activeSessions = sessionDAO.getActiveSessions();
//
//        for(Session session:activeSessions){
//            Teacher employee = (Teacher) session.getAttribute(token.getUsername());
//            if(employee !=null){
//                throw new AccountException("不能重复登录");
//            }
//        }

//        Session session = SecurityUtils.getSubject().getSession();
//        session.setAttribute(token.getUsername(),teacherService.getEmpByName(token.getUsername()));

        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(token.getPrincipal(),passwordInDB, salt, getName());

        return simpleAuthenticationInfo ;
    }
}
    